#include "readSimulator.h"

readSimulator::readSimulator() {

}

readSimulator::~readSimulator() {

}

void readSimulator::genReads(string refFileName, unsigned int NumOfReads, unsigned int LengthOfReads, unsigned int Errors, unsigned int NumOfChromosomes, string OutputFile, string configFile) {

	string realSeq, modifiedSeq,chromoName;
	stringstream chromoFind;
	int k,loc,location,endLoc;
	RefDB r;

	r.loadRefFile(refFileName);

	writeFile.open(OutputFile.c_str());
	srand (time(NULL));
	readConfigFile.open(configFile.c_str());
	while(readConfigFile >> location){
		intervals.push_back(location);
	}
	cout << "interval done" <<endl;
	readConfigFile.close();

	for (int i=0; i< NumOfChromosomes;i++){
		r.loadChromo(i);
		k=0;
		cout << "i : "<<i << "chromoMap[i] : " <<r.chromoMap[i] <<endl ;
		for(int j=0; j< NumOfReads/NumOfChromosomes;j++){


			/*while(getRefBase(k,1)=='N'){
				k++;
			}
			do{
			loc = k + (rand() % (r.getChromoLength-k));
			}while(getRefBase(loc,LengthOfReads)=='N')
			*/
			loc =rand()% r.getChromoLength();
			while(!(checkIfCorrectSeq(r.getRefSeq(loc,LengthOfReads)))){
				loc =rand()% r.getChromoLength();
			}
			cout <<"loc is " <<loc <<endl;
			realSeq=r.getRefSeq(loc,LengthOfReads);
			cout <<realSeq <<endl;
			modifiedSeq=replaceBaseUniformly(realSeq);
			cout <<modifiedSeq <<endl;
			endLoc =loc+LengthOfReads;
			writeFile << "@" <<r.chromoMap[i] <<"_"<<loc<<"_"<<endLoc<<endl;
			writeFile <<modifiedSeq <<endl <<"+" <<endl;

			for (int index=0;index<modifiedSeq.size();index ++){
				writeFile <<"I";
			}
			writeFile << endl;
			cout << "written " << loc << endl;

		}

	}
	writeFile.close();
}
bool readSimulator::checkIfCorrectSeq(string seq){

	for (int i=0 ; i<seq.size();i++){
		if(!((seq[i]=='A')||(seq[i]=='C')||(seq[i]=='T')||(seq[i]=='G')))
			return false;
	}
	return true;
}
string readSimulator::replaceBaseUniformly(string realSeq){

	for(int i=0;i<intervals.size();i++){
		realSeq[intervals[i]]=findReplacement(realSeq[intervals[i]]);

	}
	return(realSeq);
}

char readSimulator::findReplacement(char base){
	int flag=-1;

	switch(base){
	case 'A':
			return 'T';
	case 'C':
			return 'G';
	case 'T':
			return 'A';
	case 'G':
			return 'C';
	default:
			return 'A';
	}
}

